package com.zjj.lbw.algorithm.dp;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author zhanglei.zjj
 * @description Leetcode_42. 接雨水
 * @date 2023/7/19 16:50
 */
public class TrappingRainWater_leetcode42 {
    // 双指针实现
    public int trap(int[] height) {
        int ans = 0;
        int left = 0, right = height.length - 1;
        int leftMax = 0, rightMax = 0;
        while (left < right) {
            leftMax = Math.max(leftMax, height[left]);
            rightMax = Math.max(rightMax, height[right]);
            if (height[left] < height[right]) {
                ans += leftMax - height[left];
                ++left;
            } else {
                ans += rightMax - height[right];
                --right;
            }
        }
        return ans;
    }

    // 单调栈实现
    public int trap1(int[] height) {
        Deque<Integer> stack = new LinkedList<Integer>();
        int ans = 0;
        for (int i = 0; i < height.length; i++) {
            while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
                // 递增趋势的最后一个元素也就是谷底
                int top = stack.pop();
                if (stack.isEmpty()) {
                    continue;
                }
                // 谷底的左边元素
                int left = stack.peek();
                int width = i - left - 1;
                ans += (Math.min(height[left], height[i]) - height[top]) * width;
            }
            stack.push(i);
        }
        return ans;
    }

    // 动态规划实现
    public int trap2(int[] height) {
        int n = height.length;
        if (n == 0) {
            return 0;
        }
        int ans = 0;
        int[] leftdp = new int[n];
        int[] rightdp = new int[n];
        leftdp[0] = height[0];
        rightdp[n - 1] = height[n - 1];

        // 正向遍历数组填充DP数组leftDp
        for (int i = 1; i < n; i++) {
            leftdp[i] = Math.max(leftdp[i - 1], height[i]);
        }
        // 反向遍历数组填充DP数组rightDp
        for (int i = n - 2; i >= 0; i--) {
            rightdp[i] = Math.max(rightdp[i + 1], height[i]);
        }
        // 遍历每个下标位置即可得到能接的雨水总量
        for (int i = 1; i < n; i++) {
            ans += Math.min(leftdp[i], rightdp[i]) - height[i];
        }

        return ans;

    }
}
